<template>
  <div class="cont-area">
    <el-form :inline="true" :model="form" class="demo-form-inline">
      <el-form-item label="名称">
        <el-input v-model="form.name" placeholder="请输入" size="small"></el-input>
      </el-form-item>
      <el-form-item label="任务ID">
        <el-input v-model="form.id" placeholder="请输入" size="small"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search" size="mini" v-hasPermi="['bigdata:job:list']">查询</el-button>
        <el-button type="primary" @click="reset" size="mini">重置</el-button>
      </el-form-item>
      <el-form-item class="fr">
        <el-button type="danger" @click="handleDel()" size="mini" :disabled="this.multipleSelection.length < 1"
          v-hasPermi="['bigdata:job:remove']">批量删除</el-button>
      </el-form-item>
    </el-form>
    <div ref="tableAreaRef" class="table-area">
      <el-table ref="multipleTable" :data="list" tooltip-effect="dark" style="width: 100%" v-loading="isLoading"
        @selection-change="handleSelectionChange" :height="tableHeight">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="job_id" label="任务ID" show-overflow-tooltip></el-table-column>
        <el-table-column prop="job_name" label="名称" show-overflow-tooltip></el-table-column>
        <el-table-column prop="engine_name" label="资源" show-overflow-tooltip> </el-table-column>
        <el-table-column prop="project_name" label="项目名称" show-overflow-tooltip> </el-table-column>
        <el-table-column prop="job_type" label="工作流类型" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ getJobType(scope.row.job_type) }}
          </template>
        </el-table-column>
        <el-table-column prop="user" label="创建人" show-overflow-tooltip> </el-table-column>
        <el-table-column prop="start_time" label="开始时间" show-overflow-tooltip :formatter="formateDate">
        </el-table-column>
        <el-table-column prop="duration" label="运行时间" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.duration }}ms
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template slot-scope="scope">
            <div class="statusBox">
              <i class="dot" :class="getJobTag(scope.row.status).type"></i>
              <span>{{ getJobTag(scope.row.status).text }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="210">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="getCode(scope.row)"
              v-hasPermi="['bigdata:job:query']">查看</el-button>
            <el-button v-if="scope.row.status != '0'" type="text" size="small" @click="handleStart(scope.row)"
              v-hasPermi="['bigdata:job:start']">启动</el-button>
            <el-button v-if="scope.row.status == '0'" type="text" size="small" @click="handleStop(scope.row)"
              class="stopBtn" v-hasPermi="['bigdata:job:stop']">停止</el-button>
            <el-button type="text" size="small" @click="handleDel(scope.row)" class="danger"
              v-hasPermi="['bigdata:job:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <Pagination :totalSize="totalSize" :page.sync="pageInfo.pageNo" :limit.sync="pageInfo.pageSize"
      @getList="getList" />
  </div>
</template>

<script>
import { Vue, Component, Watch } from 'vue-property-decorator'
import { mapActions, mapMutations, mapState } from 'vuex'
import { cloneDeep } from 'lodash'
import moment from 'moment'
import Pagination from '@/components/Pagination'

@Component({
  components: {
    Pagination
  },
  methods: {
    ...mapActions({
      getJobList: 'GET_JOB_LIST',
      deleteJobs: 'DELETE_JOBS',
      cancelExcuteCell: 'CANCEL_EXCUTE_CELL',
      startExcute: 'START_EXCUTE'
    }),
    ...mapActions('CodeModal', {
      callCodeModal: 'CALL_MODAL'
    })
  }
})

export default class JobPage extends Vue {
  list = []
  multipleSelection = []
  isLoading = false
  tableHeight = 400
  totalSize = 0
  form = {
    name: '',
    id: ''
  }
  pageInfo = {
    pageNo: 1,
    pageSize: 10,
  }

  get statusFiltersList() {
    return [
      { text: '运行中', value: '0', type: 'running' },
      { text: '成功', value: '1', type: 'success' },
      { text: '失败', value: '2', type: 'err' },
      { text: '停止', value: '3', type: 'stop' },
      { text: '重试', value: '4', type: 'retry' }
    ]
  }
  getJobTag(status) {
    const statusItem = this.statusFiltersList.find(v => v.value === status)
    return { text: statusItem.text, type: statusItem.type }
  }
  getJobType(type) {
    return type == 'workflow' ? '流式任务' : '批量任务'
  }
  formateDate(row, column, time) {
    return moment(Number(time)).format('yyyy-MM-DD HH:mm:ss')
  }
  getCode(row) { // 只能查看原始的code 不能查看正在运行中的 code
    this.callCodeModal({ id: row.job_id, type: 'job', content: row.content })
  }
  async handleStart(row) {
    try {
      let id = row.job_id
      const res = await this.startExcute(id)
      if (res.code == 100000) {
        this.msgSuccess('操作成功')
        this.search()
      }
      // this.checkResCode(res.code, this.search)
    } catch (e) {
      console.log(e)
    }
  }
  async handleStop(row) {
    this.$confirm(
      '您确定要停止此任务吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(async () => {
      this.confirmStopJob(row)
    })
  }
  async confirmStopJob(row) {
    try {
      let ids = row ? [row.job_id] : this.multipleSelection.map(v => v.job_id)
      const res = await this.cancelAll(ids)
      if (res[0].code == 100000) {
        this.msgSuccess('操作成功')
        this.search()
      }
      // this.checkResCode(res[0].code, this.search)
    } catch (e) {
      console.log(e)
    }
  }
  async cancelAll(ids) {
    return Promise.all([...ids].map(async v => {
      return await this.cancelExcuteCell(v)
    }))
  }
  // 查询
  search() {
    this.pageInfo.pageNo = 1
    this.getList()
  }
  // 重置
  reset() {
    this.form.name = ''
    this.form.id = ''
    this.search()
  }
  // 获取列表
  async getList() {
    const pages = {
      ...this.pageInfo,
      name: this.form.name,
      jobId: this.form.id
    }
    this.isLoading = true
    const res = await this.getJobList(pages)
    if (res.code = 100000) {
      this.isLoading = false
      this.totalSize = Number(res.result.total)
      this.list = cloneDeep(res.result.records)
    }
  }
  // 多选
  handleSelectionChange(val) {
    this.multipleSelection = val;
  }
  // 删除
  handleDel(row) {
    this.$confirm(
      '您确定要删除此条数据吗？请注意，此操作无法还原。',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(async () => {
      this.confirmDelete(row)
    })
  }
  // 删除确认
  async confirmDelete(row) {
    try {
      let ids = row ? [row.id] : this.multipleSelection.map(v => v.id)
      const res = await this.deleteJobs(ids)
      if (res.code == 100000) {
        this.msgSuccess('操作成功')
        this.search()
      }
      // this.checkResCode(res.code, this.search)
    } catch (e) {
      console.log(e)
    }
  }
  mounted() {
    this.search()
    this.$nextTick(() => {
      this.tableHeight = this.$refs.tableAreaRef.clientHeight
    })
  }
}
</script>
<style lang="scss" scoped>
.cont-area {
  display: flex;
  flex-direction: column;
  height: 100%;

  .table-area {
    flex: 1;
    overflow: hidden;
    // margin-bottom: 5px;
  }

  .el-form {
    height: 40px;
    box-shadow: 0px 1px 6px -2px rgb(51, 51, 51);
    padding: 0 10px;
    margin-bottom: 5px;
  }
}

.statusBox {
  display: flex;
  justify-content: start;
  align-items: center;

  .dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    margin-right: 8px;

    &.success {
      background: #00B929;
    }

    &.running {
      background: #2AB5F0;
    }

    &.err {
      background: #D33232;
    }

    &.stop {
      background: #FF7E06;
    }

    &.retry {
      background: #fff;
    }
  }
}

.stopBtn {
  color: #FF7E06;
}
</style>
